package com.vedana.bankmobile;

import java.util.List;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import com.google.protobuf.ServiceException;
import com.vedana.bankmobile.protobuf.client.HttpRpcChannel;
import com.vedana.bankmobile.shared.Account;
import com.vedana.bankmobile.shared.Customer;
import com.vedana.bankmobile.shared.protobuf.BankProto.AccountListRequest;
import com.vedana.bankmobile.shared.protobuf.BankProto.AccountListResponse;
import com.vedana.bankmobile.shared.protobuf.BankProto.BankMobileService;
import com.vedana.bankmobile.shared.protobuf.BankProto.CustomerListRequest;
import com.vedana.bankmobile.shared.protobuf.BankProto.CustomerListResponse;
import com.vedana.bankmobile.shared.protobuf.serializers.AccountSerializer;
import com.vedana.bankmobile.shared.protobuf.serializers.CustomerSerializer;

/**
 * Customers / accounts display activity
 * 
 * @author Didier MOISE
 *
 */
public class AccountsActivity extends ListActivity {
    /** Tag for logging. */
    private static final String TAG = "OperationsActivity";

    private HttpRpcChannel channel=new HttpRpcChannel(Constants.SERVER_URL);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "onCreate");
		super.onCreate(savedInstanceState);

		setContentView(R.layout.accounts);
		
		new LoadAccountsTask().execute("smith");
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	/**
     * Asynchronous task to load customers and accounts
     */
    private class LoadAccountsTask extends AsyncTask<String, Void, List<Customer>> {
    	private ProgressDialog progressDialog;
    	private Exception exception = null;
    	
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = ProgressDialog.show(AccountsActivity.this, "", "Loading", true);
		}

		@Override
		protected List<Customer> doInBackground(String... userId) {
			try {
				BankMobileService.BlockingInterface stub = BankMobileService.newBlockingStub(channel);
				CustomerListRequest request = CustomerListRequest.newBuilder().setUserId(userId[0]).build();
				CustomerListResponse msg = stub.getCustomerList(null, request);
				
				// Convert protobuf Msg to model objects.		
				final List<Customer> customers = CustomerSerializer.readListFromMsg(msg.getCustomersList());
				
				// Load customer accounts
				for (Customer customer : customers) {
					loadAccounts(customer);
				}

				return customers;
			} 
			catch (Exception ex) {
				exception = ex;
				return null;
			}
		}

		/**
		 * Load accounts for a customer (asynchronous).
		 * @param customer Customer holding the accounts
		 * @param gridView Gridview for result display
		 */
		private void loadAccounts(Customer customer) throws ServiceException {
			BankMobileService.BlockingInterface stub = BankMobileService.newBlockingStub(channel);
			AccountListRequest request = AccountListRequest.newBuilder().setCustomerId(customer.getId()).build();
			AccountListResponse msg = stub.getAccountList(null, request);
			
			// Convert protobuf Msg to model objects.
			List<Account> accounts = AccountSerializer.readListFromMsg(msg.getAccountsList());
			customer.setAccounts(accounts);
		}

		@Override
		protected void onPostExecute(List<Customer> result) {
			super.onPostExecute(result);

			progressDialog.dismiss();

			// Display exception
			if (exception != null) {
				AlertDialog.Builder dlg = new AlertDialog.Builder(AccountsActivity.this);
				dlg.setMessage("Cannot connect to BankMobile server");
				dlg.setNeutralButton("Ok", null);
				dlg.create().show();
				
				return;
			}
			
			// Create an CustomersAdapter, that will actually make the operations
			// appear in the ListView
			AccountsActivity.this.setListAdapter(new CustomersAdapter(AccountsActivity.this, result));			
		}
    }
}
